package com.snowfield.lb47.lbconfig.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.snowfield.lbcommon.config.SnowFieldConfig;
import com.snowfield.lb47.lbconfig.domain.BackserverCrt;
import com.snowfield.lb47.lbconfig.service.IBackserverCrtService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 服务器证书Controller
 *
 * @author snowfield
 * @date 2024-03-25
 */
@RestController
@RequestMapping("/lbconfig/servercrt")
public class BackserverCrtController extends BaseController {
    @Autowired
    private IBackserverCrtService backserverCrtService;

    private static final Logger LOGGER = LoggerFactory.getLogger(BackserverCrtController.class);

    /**
     * 查询服务器证书列表
     */
    @PreAuthorize("@ss.hasPermi('lbconfig:servercrt:list')")
    @GetMapping("/list")
    public TableDataInfo list(BackserverCrt backserverCrt) {
        startPage();
        List<BackserverCrt> list = backserverCrtService.selectBackserverCrtList(backserverCrt);
        return getDataTable(list);
    }

    /**
     * 导出服务器证书列表
     */
    @PreAuthorize("@ss.hasPermi('lbconfig:servercrt:export')")
    @Log(title = "服务器证书", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BackserverCrt backserverCrt) {
        List<BackserverCrt> list = backserverCrtService.selectBackserverCrtList(backserverCrt);
        ExcelUtil<BackserverCrt> util = new ExcelUtil<BackserverCrt>(BackserverCrt.class);
        util.exportExcel(response, list, "服务器证书数据");
    }

    /**
     * 获取服务器证书详细信息
     */
    @PreAuthorize("@ss.hasPermi('lbconfig:servercrt:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(backserverCrtService.selectBackserverCrtById(id));
    }

    /**
     * 新增服务器证书
     */
    @PreAuthorize("@ss.hasPermi('lbconfig:servercrt:add')")
    @Log(title = "服务器证书", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BackserverCrt backserverCrt) {

        if (!backserverCrtService.checkPortUnique(backserverCrt)) {
            return AjaxResult.error("本服务器端口 '" + backserverCrt.getCrtPort() + "' 证书已存在");
        }
        /**
         * 将上传的服务器证书文件拷贝到 /serverCrt/目录下，并修改文件名称
         */

        String crtUploadPath = backserverCrt.getCrtUploadPath();
        if (StringUtils.isEmpty(crtUploadPath)) {
            return AjaxResult.error("服务器证书文件未上传");
        }
        crtUploadPath = crtUploadPath.replace("/profile", "");
        File crtUploadFile = new File(FileUploadUtils.getDefaultBaseDir() + crtUploadPath);
        if (!crtUploadFile.exists()) {
            return AjaxResult.error("服务器证书文件上传异常");
        }

        String crtFileName = backserverCrt.getServerId() + crtUploadFile.getName().substring(crtUploadFile.getName().lastIndexOf("_"));
        String crtPath = SnowFieldConfig.getServerCrtPath() + "/" + crtFileName;
        try {
            FileUtils.copyFile(crtUploadFile, new File(crtPath));
            backserverCrt.setCrtPath(crtPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return toAjax(backserverCrtService.insertBackserverCrt(backserverCrt));
    }

    /**
     * 修改服务器证书
     */
    @PreAuthorize("@ss.hasPermi('lbconfig:servercrt:edit')")
    @Log(title = "服务器证书", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BackserverCrt backserverCrt) {
        if (!backserverCrtService.checkPortUnique(backserverCrt)) {
            return AjaxResult.error("本服务器端口 '" + backserverCrt.getCrtPort() + "' 证书已存在");
        }
        /**
         * 判断修改数据是否对证书文件进行了修改，如果进行了修改，要更新原来服务器的证书文件
         */
        BackserverCrt oldOne = backserverCrtService.selectBackserverCrtById(backserverCrt.getId());
        String crtUploadPath = backserverCrt.getCrtUploadPath();
        if (!StringUtils.isEmpty(crtUploadPath)) {
            crtUploadPath = crtUploadPath.replace("/profile", "");
            File crtUploadFile = new File(FileUploadUtils.getDefaultBaseDir() + crtUploadPath);
            if (!crtUploadFile.exists()) {
                return AjaxResult.error("服务器证书文件上传异常");
            }

            String crtFileName = backserverCrt.getServerId() + crtUploadFile.getName().substring(crtUploadFile.getName().lastIndexOf("_"));
            String crtPath = SnowFieldConfig.getServerCrtPath() + "/" + crtFileName;
            try {
                FileUtils.copyFile(crtUploadFile, new File(crtPath));
                backserverCrt.setCrtPath(crtPath);

                //删除旧的服务器证书文件
                File oldCrtFile = new File(oldOne.getCrtPath());
                if (oldCrtFile.exists()) {
                    FileUtils.deleteQuietly(oldCrtFile);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return toAjax(backserverCrtService.updateBackserverCrt(backserverCrt));
    }

    /**
     * 删除服务器证书
     */
    @PreAuthorize("@ss.hasPermi('lbconfig:servercrt:remove')")
    @Log(title = "服务器证书", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(backserverCrtService.deleteBackserverCrtByIds(ids));
    }

    /**
     * 上传服务器证书
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @PreAuthorize("@ss.hasPermi('lbconfig:servercrt:import')")
    @Log(title = "服务器证书", businessType = BusinessType.IMPORT)
    @PostMapping("/uploadCrt")
    public AjaxResult uploadCrt(MultipartFile file, boolean updateSupport) throws Exception {
        if (!file.isEmpty()) {
            String crtFile = FileUploadUtils.upload(file);
            if (StringUtils.isNotEmpty(crtFile)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("crtUrl", crtFile);
                return ajax;
            }
        }
        return error("上传服务器证书异常，请联系管理员");
    }

    /**
     * 下载服务器证书文件
     */
    @PreAuthorize("@ss.hasPermi('lbconfig:servercrt:export')")
    @Log(title = "服务器证书", businessType = BusinessType.EXPORT)
    @PostMapping("/downloadCrt/{id}")
    public void downloadCrt(HttpServletResponse response, @PathVariable("id") Long id) {
        BackserverCrt backserverCrt = backserverCrtService.selectBackserverCrtById(id);
        if (backserverCrt != null) {
            File crtFile = new File(backserverCrt.getCrtPath());
            if (crtFile.exists()) {
                try {
                    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                    response.setCharacterEncoding("utf-8");
                    FileUtils.copyFile(crtFile, response.getOutputStream());
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }

}
